<script setup>
import _ from 'lodash';

import MenusTreeTree from './menus-tree-tree.vue';
import { computed, nextTick, onMounted, reactive, ref, toRefs, watch } from 'vue';
import { api } from '@jzl/api';
import { DFT_ICONS } from '@jzl/icons';
import { $utils, $menuUtils, execFn } from '@jzl/utils';
import FormPermission from '@/views/basic/menus/form-permission.vue';
import FormApp from '@/views/basic/menus/form-app.vue';
import FormMenu from '@/views/basic/menus/form-menu.vue';
import FormGroup from '@/views/basic/menus/form-group.vue';
import { isAppForm, isGroupForm, isMenuForm, isPermissionForm } from '../../../common/common.js';

const emit = defineEmits(['close', 'select', 'click-blank']);
const props = defineProps({
  appId: Number,
  selectedId: [Number, String]
});

const {
  tty,
  items,
  loading,
  tid,
  portalDataList,
  appDataList,

  actionType,
  menuFormWinName,
  menuFormShow,
  menuForm
} = toRefs(
  reactive({
    tty: 1,
    items: [],
    loading: false,
    tid: null,
    portalDataList: [],
    appDataList: [],

    actionType: 'view', // createGroup | createMenu | edit | view
    menuFormWinName: '',
    menuFormShow: false,
    menuForm: null
  })
);
const collapseActiveNames = ref([ 'api', 'portal', 'app' ]);

watch(
  () => [props.appId, tty.value],
  () => {
    init();
  }
);

watch(tty, () => {
  collapseActiveNames.value = [ 'api', 'portal', 'app' ];
})

/*watch(
  () => queryText.value,
  () => {
    menutreeRef.value.filter(val);
  }
);*/

onMounted(() => {
  init();
});

// 递归遍历树
const filterTreeByProp = (node, childProp = 'children') => {
  if(_.isArray(node)) {
    return node.filter(n => !$menuUtils.isApp(n) && !$menuUtils.isAppGroup(n)).map(n => {
      if(n?.[ childProp ]?.length) {
        n[ childProp ] = filterTreeByProp(n[ childProp ], childProp);
      }
      return n;
    })
  } else {
    if($menuUtils.isApp(node) && !$menuUtils.isAppGroup(n)) {
      return null;
    }
    // 递归遍历子节点
    if (node?.[ childProp ]?.length > 0) {
      node[ childProp ] = filterTreeByProp(node?.[ childProp ], childProp); // 确保子节点按顺序处理
      return node;
    }
  }
  return node;
}

const getPortalDataList = () => {
  let dataList = _.cloneDeep(items.value);
  let newList = filterTreeByProp(dataList, 'subs')
  return newList;
}

const getAppDataList = async () => {
  console.log(`------------>>>>>> getAppDataList...`)
  let dataList = _.cloneDeep(items.value);
  let newList = [];

  await $utils.traverseTree(dataList, (node, nodeList, index) => {
    if($menuUtils.isApp(node)) {
      newList.push(node)
    }
  }, 'subs');

  return newList;
}

const init = async () => {
  let menutree;

  loading.value = true;

  if (props.appId) {
    let mySub = await api.menu.getSubMenuTree(props.appId, tty.value);

    // 只显示子菜单
    // menutree = _.get(mySub, '[0].subs', []);
    menutree = mySub || [];
  } else {
    menutree = await api.menu.getMenuTree(tty.value);
  }

  items.value = menutree || [];
  portalDataList.value = getPortalDataList();
  appDataList.value = await getAppDataList();
  // 默认展开一级菜单
  // expandedKeys.value = _.map(menutree, 'tid');
  loading.value = false;
};

const handleSelectNode = (nodeData) => {
  emit('select', nodeData);
  tid.value = nodeData?.tid;
}

const handleBeforeCollapse = (activeName) => {
  if(activeName === 'api') return false;
  return true;
}

const handleShowCreateApp = () => {
  actionType.value = 'createApp'; // createGroup | createMenu | edit | view
  menuFormShow.value = true;
  menuFormWinName.value = `新增应用`;
};

const handleShowCreateRoot = (cmd) => {
  if (cmd === 'group') {
    // handleShowCreateGroupRoot();
    handleActionCreate(null, 'createGroup');
  } else if (cmd === 'menu') {
    if (tty.value !== 1 && tty.value !== 2 && tty.value !== 3) {
      return $jui.toast('先选择正确的菜单类型');
    }
    // handleShowCreateMenuRoot();
    handleActionCreate(null, 'createMenu');
  } else if (cmd === 'api') {
    handleActionCreate(null, 'createPermission');
  }
};

const handleActionCreate = (data, acType) => {
  menuForm.value = data;
  actionType.value = acType;

  let prefixName = '';
  if(menuForm.value?.tid) {
    let paths = $utils.getTreePath(menuForm.value.tid, items.value, 'tid', 'subs', true);
    prefixName = `在【${ _.join(_.map(paths, 'group_name'), '/') }】下新增`;

    console.log(`----> paths: `, paths, menuForm.value)
  } else {
    prefixName = '新增根';
  }

  if(acType === 'createMenu') {
    menuFormWinName.value = `${ prefixName }菜单`;
  } else if(acType === 'createGroup') {
    menuFormWinName.value = `${ prefixName }分组`;
  } else if(acType === 'createApp') {
    menuFormWinName.value = `${ prefixName }应用`;
  } else if(acType === 'createPermission') {
    menuFormWinName.value = `${ prefixName }权限`;
  }

  menuFormShow.value = true;

  // console.log(data, acType)
}

const handleActionUpdate = (data) => {
  menuForm.value = data;
  // actionType.value = acType;

  let name = $menuUtils.isMenu(menuForm.value)
    ? menuForm.value.content_name
    : menuForm.value.group_name;

  actionType.value = 'edit';
  menuFormShow.value = true;
  menuFormWinName.value = `修改【${name}】`;
}

const handleActionRemove = async (chgTid) => {
  tid.value = chgTid;
  await init();
}

const handleRefreshTid = (chgTid) => {
  tid.value = chgTid;
}

const handleCancel = () => {
  menuFormShow.value = false;
};

const handleSuccess = async (modifyId) => {
  // refreshCurrentNode(tid);
  menuFormShow.value = false;

  await init();
  tid.value = modifyId;
};

</script>
<template>
  <div v-jloading="loading" class="apps-menu-container">
    <div class="apps-menu-actions">
      <div
        class="apps-menu-actionitem"
        :class="{ active: tty === 0 }"
        @click="tty = 0"
      >所有</div>
      <div
        class="apps-menu-actionitem"
        :class="{ active: tty === 1 }"
        @click="tty = 1"
      >管理</div>
      <div
        class="apps-menu-actionitem"
        :class="{ active: tty === 3 }"
        @click="tty = 3"
      >WEB</div>
      <div
        class="apps-menu-actionitem"
        :class="{ active: tty === 2 }"
        @click="tty = 2"
      >手机</div>
      <div
        class="apps-menu-actionitem"
        :class="{ active: tty === 9 }"
        @click="tty = 9"
      >接口</div>
      <!--<div class="apps-menu-actionitem none" @click="handleShowCreateGroupRoot">
          <i class="el-icon-plus"></i> &nbsp;分组1
      </div>
      <div class="apps-menu-actionitem none" @click="handleShowCreateMenuRoot"
           style="border-left: 1px solid #F1F1F1;">
          <i class="el-icon-plus"></i> &nbsp;菜单1
      </div>-->
    </div>
    <!--    <el-input
      v-model="queryText"
      size="small"
      class="thin-search-input"
      clearable
      placeholder="按名称搜索"
    />-->
    <div class="flex flex-col align-center flex-1 h-full overflow-auto">
      <el-collapse
        v-model="collapseActiveNames"
        expand-icon-position="left"
        :before-collapse="handleBeforeCollapse"
      >
        <el-collapse-item
          name="api"
          v-if="tty == 9"
        >
          <template #title="{ isActive }">
            <div
              class="flex justify-between items-center"
              :class="['title-wrapper', { 'is-active': isActive }]"
            >
              <span>接口菜单（用于控制权限）</span>

              <el-dropdown
                trigger="click"
                placement="right-start"
                size="small"
                @command="handleShowCreateRoot"
              >
                <JIcon
                  :icon="DFT_ICONS.add"
                  class="menu-add-icon"
                />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="group">
                      <JIcon :icon="DFT_ICONS.add" />
                      根分组
                    </el-dropdown-item>
<!--                    <el-dropdown-item command="menu">
                      <JIcon :icon="DFT_ICONS.add" />
                      菜单
                    </el-dropdown-item>-->
                    <el-dropdown-item command="api">
                      <JIcon :icon="DFT_ICONS.add" />
                      接口
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          <MenusTreeTree
            :app-id="appId"
            :tree-data="portalDataList"
            :tty="tty"
            :tid="tid"
            @select="handleSelectNode"
            @action-create="handleActionCreate"
            @action-update="handleActionUpdate"
            @action-remove="handleActionRemove"
            @refresh-tid="handleRefreshTid"
          />
        </el-collapse-item>
        <el-collapse-item
          name="portal"
          v-if="tty != 9 && !appId"
        >
          <template #title="{ isActive }">
            <div
              class="flex justify-between items-center"
              :class="['title-wrapper', { 'is-active': isActive }]"
            >
              <span>门户菜单（主框架显示的菜单）</span>
              <el-dropdown
                trigger="click"
                placement="right-start"
                size="small"
                @command="handleShowCreateRoot"
              >
                <JIcon
                  :icon="DFT_ICONS.add"
                  class="menu-add-icon"
                  @click.stop
                />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="group">
                      <JIcon :icon="DFT_ICONS.add" />
                      根分组
                    </el-dropdown-item>
                    <el-dropdown-item command="menu">
                      <JIcon :icon="DFT_ICONS.add" />
                      根菜单
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          <MenusTreeTree
            :app-id="appId"
            :tree-data="portalDataList"
            :tty="tty"
            :tid="tid"
            @select="handleSelectNode"
            @action-create="handleActionCreate"
            @action-update="handleActionUpdate"
            @action-remove="handleActionRemove"
          />
        </el-collapse-item>
        <el-collapse-item
          name="app"
          v-if="tty != 9"
        >
          <template #title="{ isActive }">
            <div
              class="flex justify-between items-center"
              :class="['title-wrapper', { 'is-active': isActive }]"
            >
              <span>应用菜单（应用内显示的菜单）</span>
<!--              <el-dropdown
                trigger="click"
                placement="bottom-start"
                @command="handleShowCreateRoot"
              >
                <JIcon
                  :icon="DFT_ICONS.add"
                  class="menu-add-icon"
                  @click.stop
                />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="group">
                      <JIcon :icon="DFT_ICONS.add" />
                      分组
                    </el-dropdown-item>
                    <el-dropdown-item command="menu">
                      <JIcon :icon="DFT_ICONS.add" />
                      菜单
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>-->
            </div>
          </template>
          <MenusTreeTree
            :app-id="appId"
            :tree-data="appDataList"
            :tty="tty"
            :tid="tid"
            @select="handleSelectNode"
            @action-create="handleActionCreate"
            @action-update="handleActionUpdate"
            @action-remove="handleActionRemove"
          />
        </el-collapse-item>
      </el-collapse>
<!--      <div class="flex flex-1 flex-col overflow-hidden">
        <b class="app-menu-group-title"></b>

      </div>
      <div class="flex flex-1 flex-col overflow-hidden">
        <b class="app-menu-group-title"></b>

      </div>-->
    </div>

    <el-dialog
      v-model="menuFormShow"
      :title="menuFormWinName"
      top="40px"
      custom-class="m-dialog-style"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <div style="padding: 10px 30px 5px; background: #fff">
        <FormGroup
          v-if="isGroupForm(menuForm, actionType)"
          :action-type="actionType"
          :current-data="menuForm"
          :tty="tty"
          :app-id="appId"
          @success="handleSuccess"
          @cancel="handleCancel"
        />
        <FormPermission
          v-else-if="isPermissionForm(menuForm, actionType)"
          :action-type="actionType"
          :current-data="menuForm"
          :tty="tty"
          @success="handleSuccess"
          @cancel="handleCancel"
        />
        <FormMenu
          v-else-if="isMenuForm(menuForm, actionType)"
          :action-type="actionType"
          :current-data="menuForm"
          :tty="tty"
          :app-id="appId"
          @success="handleSuccess"
          @cancel="handleCancel"
        />
        <FormApp
          v-else-if="isAppForm(menuForm, actionType)"
          :action-type="actionType"
          :current-data="menuForm"
          :tty="tty"
          :app-id="appId"
          @success="handleSuccess"
          @cancel="handleCancel"
        />
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.app-menu-group-title {
  padding: 5px 10px;
  font-size: 12px;
  background: var(--j-fill-color);
  border-bottom: 1px solid var(--j-border-color-lighter);
}
.menu-add-icon {
  border: 1px solid var(--j-border-color-lighter);
  border-radius: 4px;
  margin-right: 5px;
  width: 18px;
  height: 18px;

  &:hover {
    border-color: var(--j-border-color);
  }
}
:deep(.el-collapse-item__header) {
  line-height: 30px;
  min-height: 30px;
  padding-left: 8px;
  gap: 5px;
}
:deep(.el-collapse-item:last-child .el-collapse-item__wrap) {
  border-bottom: none;
}
:deep(.el-collapse-item__header .el-icon) {
  width: 10px;
}
</style>
